#! /usr/bin/env python
# -*- coding: utf-8 -*-

import re
import os
import time
import json
import traceback
import urlparse

import requests
from requests.compat import cookielib

import FileHostProtoType

class rgitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, id, link, encrypt_name='', server_name=''): 
        #id save as D111111 or F1111111 
        FileHostProtoType.HostItem.__init__(self, name, type, id, link, encrypt_name, server_name)

DEFAULT_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2'
DEFAULT_REFERER = 'http://rapdigator.net/'  
COOKIEJAR_CLASS = cookielib.MozillaCookieJar  

class rapidgator(FileHostProtoType.FileHostProcess):
    def __init__(self,user,pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "RapidGator"
        self.logtype = 'poster'
        self._opener = None
        self._cj = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self._cookieCurl = self._user + '_RapidGator.cookie'
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
        
        self._cj = COOKIEJAR_CLASS(self._cookieCurl)
        self.session = requests.session(cookies=self._cj)
        self.session.headers['User-Agent'] = DEFAULT_USER_AGENT
        self.session.headers['Referer'] = DEFAULT_REFERER
        if self.proxy:
            self.session.proxies = {'http':self.proxy}
    

    def meta_refresh_rediect(self, url, response):
        if "http-equiv='refresh'" in response:
            self.fherr.write(response)
            s_pos = response.find('url=')
            e_pos = response.find("'>", s_pos)
            new_url = urlparse.urljoin(url, response[s_pos+4:e_pos])
            self.fherr.write(new_url)
            return new_url
        return url
        
    def login(self):
        '''
        login to FileSonic
        return opener object which includes cookies
        '''
        # if self.islogin == True:
            # return True
        
        #initial: generate opener and cookiejar, get domain name.
#        self.get_domain()
        self.generateOpener()
        #try to restore cookiejar
        if self.restore_cookiejar():
            return True
        
        self.fherr.write('login to RapidGator %s/%s...' % (self._user,'*'*len(self._pwd)))
        loginData = {'LoginForm[email]' : self._user, \
                     'LoginForm[password]' : self._pwd, \
                     'LoginForm[rememberMe]' : '1'}
        response = self.tb_request("http://rapidgator.net/auth/login", loginData)
        cookie_status = self.check_cookie()
        if not cookie_status:
            self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
            self.fherr.write(response)
            return False
        self.fherr.write('write cookie file.')
        try:
            os.remove(self._cookieCurl)
        except:
            self.fherr.write('Exception occured when deling Local Cookie.')
        self._cj.save(ignore_discard=True)
        return True   
        
    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False
    
    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.tb_request('http://rapidgator.net/profile/index')
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        self.fherr.write(response)
        return False
    
    def getFileList(self):
        return self.exportLinks()
    
    def getFilesFromFolder(self, folder):
        id  = folder.id
        return []
    
    def getFolderList(self):   
        foundFolders = []
        foundFolders.sort()
        return foundFolders 

    def createFolder(self, newfolder):
        foundfolder = self.findFolder(newfolder)
        if foundfolder is None:
            #rapidgator no longer allow user to create subdir 
            return self.__newFolder(newfolder)
        self.fherr.write("Folder %s exsits." % newfolder)
        return foundfolder

    def __newFolder(self, newfolder, parentfolder=None):
        return None
    
    def moveto(self, items, destFolder):
        if len(items) == 0:
            return
        url = "http://rapidgator.net/filesystem/MoveSelected"
        data = []
        for i in items:
            if i.id:
                data.append(('id',i.id))  
        if not 	data:
            self.fherr.write("No file to move")    
            return		
        data.append(('id_move_to',destFolder.id))
        self.fherr.write(str(data))
        response = self.tb_request(url, data)
        if "true" in response:
            self.fherr.write("Moved.")
            
    def upload_web(self, file, progressLog=None, other_args=None):
        return self.upload_web_local(file, progressLog, other_args)    
    
    def upload_to_ftp(self, file, progressLog=None, other_args=None):
        self.fherr.write("ftp mode is not impl.")
        return None
    
    def upload_web_local(self, file, progressLog=None, other_args=None, send_range=None):
        #upload page           
        uploadpage = self.tb_request("http://rapidgator.net/")
                
        serverlink = self.get_upload_key(uploadpage, "form_url", -2, '"')
        progress_link = self.get_upload_key(uploadpage, 'progress_url_srv', -2, '"')
        
        uuid = self.get_random()
        
        upload_link = serverlink + uuid + "&folder_id=0"
        
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        info = "Uploading...%s" % file
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
        
        fileobj = open(file, 'rb')
        fileobj.seek(start_point) 
        
        data = {}
        data['file'] = fileobj
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        
        self.fherr.write(info)
        
        resultMsg = self.post_request(upload_link, \
                                   data, \
                                   cb=callback, \
                                   retry=1,\
                                   setfilename=filename, \
                                   setfilesize=filesize)
                    
        if resultMsg is None:
            self.fherr.write("UploadTask(%s) was Stop by user." % file)
            return
        
        while True:
            ticket = self.get_timeticket(10)
            url = progress_link + "&data[0][uuid]=%s&data[0][start_time]=%s" % (uuid, ticket) 
            progress_info = self.tb_request(url)
            if progress_info is None:
                self.fherr.write("Failed to get progress info, retry in 10s")
                time.sleep(10)
            result = json.loads(progress_info)[0]
            if result["state"] == "done":
                download_url = result["download_url"]
                remove_url = result["remove_url"]
                file_id = download_url.split('/')[4]
                item = rgitem(os.path.basename(file), 'file', file_id, download_url, filename)
                self.newupload.append(item)
                return item
            elif result['state'] == "uploading":
                continue
            else:
                self.fherr.write("Something wrong?")
                self.fherr.write(progress_info)
                break
        
    def tb_request(self, url, data=None, cookies={}):
        '''
        use requests to send request to turbobit.
        '''
        retry = 3
        while(retry  > 0):
            try:
                if data is None:
                    r = self.session.get(url, cookies=cookies)
                else:
                    r = self.session.post(url, data=data, cookies=cookies)
                time.sleep(1)
                newurl = self.meta_refresh_rediect(url, r.text)
                response = r.text
                if url != newurl:
                    response = self.tb_request(newurl, data, cookies)
                return response
            except:
                traceback.print_exc()
                print 'Fail to Get url, retry...'
                print url
                return None
            retry -= 1
    
if __name__ == "__main__":
    pass
